import axios from "axios";
import { message } from "antd";

// 最大显示数, 超过限制时，最早的消息会被自动关闭
message.config({ maxCount: 3 });

const MOCK_API =
  "https://fastmock.site/mock/d451d648bf7d24e6bcfcd03fd9bfe605/react-backstage/api/";
const whiteApi = ["login", "register", "send/code", "reset/password"];

const http = axios.create({
  baseURL: MOCK_API,
  timeout: 1000 * 60 * 3,
});

// http request 请求拦截器，有token值则配置上token值
http.interceptors.request.use(
  function (config) {
    const { url } = config;
    if (!whiteApi.includes(url)) {
      const token = window.sessionStorage.getItem("token");
      if (!token) {
        return Promise.reject({
          code: 4002,
          message: "为获取到令牌,请先登录",
          data: null,
        });
      }
      config.headers.Authorization = token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// http response 服务器响应拦截器，这里拦截401错误，并重新跳入登页重新获取token
http.interceptors.response.use(
  (response) => {
    const data = response.data;
    if (data.code === 200) {
      // 响应成功
      return data.data;
    } else {
      // 响应失败
      message.error(data.message || data.desc);
      return Promise.reject(response);
    }
  },
  (error) => {
    if (error.code === 4002) {
      message.error(error.message);
      window.location.href = "#/login";
      return Promise.reject(error);
    }
    return Promise.reject(error.message);
  }
);
export default http;
